package com.tangcheng.adapter.db.mybatis.plugin.sensitive.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

/**
 * @Auther: cheng.tang
 * @Date: 2024/8/15
 * @Description: mybatis-subject
 */
@Slf4j
public class AesBase64Util {

    public static String encrypt(String aesSecret, String content) {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] keyBytes = Arrays.copyOf(aesSecret.getBytes("ASCII"), 16);
            SecretKeySpec result = new SecretKeySpec(keyBytes, "AES");
            cipher.init(1, result);
            byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            log.error("加密失败 {}", e.getMessage());
            return content;
        }
    }


}
